package com.study.manage.repository;


import com.study.manage.pojo.Permission;
import com.study.manage.pojo.Role;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Component;

import javax.transaction.Transactional;
import java.util.List;


@Component
public interface RoleRepository extends JpaRepository<Role,Integer>, JpaSpecificationExecutor<Role> {


    @Modifying
    @Transactional
    @Query("update Role a set " +
            "a.roleName = CASE WHEN :#{#user.roleName} IS NULL THEN a.roleName ELSE :#{#user.roleName} END ," +
            "a.descpt = CASE WHEN :#{#user.descpt} IS NULL THEN a.descpt ELSE :#{#user.descpt} END ," +
            "a.code = CASE WHEN :#{#user.code} IS NULL THEN a.code ELSE :#{#user.code} END ," +
            "a.insertUid = CASE WHEN :#{#user.insertUid} IS NULL THEN a.insertUid ELSE :#{#user.insertUid} END ," +
            "a.insertTime = CASE WHEN :#{#user.insertTime} IS NULL THEN a.insertTime ELSE :#{#user.insertTime} END ," +
            "a.updateTime = CASE WHEN :#{#user.updateTime} IS NULL THEN a.updateTime ELSE :#{#user.updateTime} END " +
            "where a.id = :#{#user.id}")
    int update(@Param("user") Role user);


    /**
     * 根据用户id获取權限数据
     * @param id
     * @return
     */
    @Query("select r.permissionList" +
            " from Role as r " +
            " where r.id =:id")
    List<Permission> findPermsByRole(Integer id);


    /**
     * 批量删除角色权限中间表数据
     * @param roleId
     */
    @Transactional
    @Modifying
    @Query(value = "delete from role_permission where role_id = :roleId", nativeQuery = true)
    void batchDelRolePerms(int roleId);

    @Transactional
    @Modifying
    @Query(value = "INSERT INTO role_permission(role_id, permit_id) VALUES(?1, ?2)", nativeQuery = true)
    void saveRolePermission(int roleId, int permitId);
}
